package com.im.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.util.Date;

/**
 * 处理消息的hander SimpleChannelInboundHandler 输入事件模板类  TextWebSocketFrame 是消息的载体
 */
public class ChatHander extends SimpleChannelInboundHandler<TextWebSocketFrame> {

  //保存一组的channel 必须是static
  private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

  @Override
  protected void channelRead0(ChannelHandlerContext channelHandlerContext,
      TextWebSocketFrame msg) throws Exception {
      String context =  msg.text();
      System.out.println("channelGroup的大小是:"+channelGroup.size());
      System.out.println("传输的数据"+context);
      for (Channel channel: channelGroup) {//发送复杂的业务在这里动手
        channel.writeAndFlush(new TextWebSocketFrame("服务在"+ new Date() +"收到消息"+context));
      }
  }

  @Override
  public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    System.out.println("注册的"+ctx.channel().id().asShortText());
    super.channelRegistered(ctx);
  }

  @Override
  public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    System.out.println("注销chanel"+ctx.channel().id().asShortText());
    super.channelUnregistered(ctx);
  }

  @Override
  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("断开的channel"+ctx.channel().id().asShortText());
    super.channelInactive(ctx);
  }

  @Override
  public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    System.out.println("添加一个chanel"+ctx.channel().id().asShortText());
    channelGroup.add(ctx.channel());
    super.handlerAdded(ctx);
  }

  @Override
  public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    channelGroup.remove(ctx.channel());
    System.out.println("移除的channel的长Id"+ctx.channel().id().asLongText());
    System.out.println("移除的channel的端Id"+ctx.channel().id().asShortText());
    super.handlerRemoved(ctx);
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    super.exceptionCaught(ctx, cause);
  }
}
